<template>
  <div>
    <h1>{{ vote.question }}</h1>
    <div v-if="vote.options">
      <el-radio-group v-model="selectedOptions" v-if="vote.question_type === 'single_choice'">
        <el-radio-button v-for="option in vote.options" :key="option.id" :label="option.id">
          {{ option.content }}
        </el-radio-button>
      </el-radio-group>

      <el-checkbox-group v-model="selectedOptions" v-else>
        <el-checkbox v-for="option in vote.options" :key="option.id" :label="option.id">
          {{ option.content }}
        </el-checkbox>
      </el-checkbox-group>

      <el-button @click="submitVote" type="primary">Submit</el-button>
    </div>

    <div>
      <h2>Real-time Results</h2>
      <div id="chart" style="width: 600px; height: 400px;"></div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import * as echarts from 'echarts';

export default {
  data() {
    return {
      socket:null,
      vote: {},
      selectedOptions: [],
      chart: null
    };
  },
  async created() {
    await this.fetchVote();
    this.initChart();
     this.connectWebSocket();
  },
  beforeUnmount() { // 添加 beforeUnmount 生命周期钩子
    if (this.socket) {
      this.socket.close();
      this.socket = null;
    }
  },
  methods: {
    async fetchVote() {
      const response = await axios.get(`/api/v1/votes/${this.$route.params.id}`);
      this.vote = response.data;
    },
    initChart() {
      this.chart = echarts.init(document.getElementById('chart'));
      this.updateChart();
    },
    updateChart() {
      if(this.vote?.options){
        const options = this.vote?.options.map(opt => opt.content);
        const counts = this.vote?.options.map(opt => opt.vote_count);
      this.chart.setOption({
        title: {
          text: 'Vote Results',
          subtext: 'Real-time data'
        },
        tooltip: {},
        xAxis: {
          data: options
        },
        yAxis: {},
        series: [{
          name: 'Vote count',
          type: 'bar',
          data: counts
        }]
      });
      }
    
    },
    async submitVote() {
      const response = await axios.post(`/api/v1/votes/${this.$route.params.id}/submit`, {
        options: this.selectedOptions
      });
      this.vote = response.data;
      this.updateChart();
      this.connectWebSocket()

    },
    connectWebSocket() {
    if (this.socket) {
        this.socket.close();
        this.socket = null;
    }
    this.socket = new WebSocket('ws://localhost:8000/ws/votes/1');
    this.socket.onopen = () => {
        console.log("WebSocket connection opened");
        // 发送初始消息
        //this.socket.send(JSON.stringify({name:123}));
    };
    this.socket.onmessage = (event) => {
    try {
      console.log(event.data)
        const data = JSON.parse(event.data);
        console.log(data)
        if (event.data !== "{}") {
            this.vote = data;
            this.$nextTick(() =>{
              this.updateChart();
            })
           
        }
    } catch (e) {
        console.error("Error processing WebSocket message:", event.data);
    }
};
    this.socket.onclose = () => {
        console.log("WebSocket connection closed");
        setTimeout(this.connectWebSocket.bind(this), 5000);
    };
}
  }
};
</script>